package com.example.demo.utils.sql;

import com.example.demo.utils.date.DateUtils;
import com.example.demo.utils.common.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.sql.Date;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;

/**
 * sql执行时间监听，基于mybatis插件来实现
 *     MyBatis 允许在已映射语句执行过程中的某一点进行拦截调用。
 * 　　默认情况下，MyBatis 允许使用插件来拦截的方法调用包括：
 * 　　①Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
 * 　　②ParameterHandler(getParameterObject, setParameters)
 * 　　③ResultSetHandler(handleResultSets, handleOutputParameters)
 * 　　④StatementHandler(prepare, parameterize, batch, update, query)
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Component
@Slf4j
public class SqlExecuteTimeInterceptor implements Interceptor {

    private Configuration configuration =null;

    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT_THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(DateUtils.yyyyMMddHHmmssSSS);
        }
    };

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        long startTime = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) target;
        try {
            return invocation.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            long timeCount = endTime - startTime;

            BoundSql boundSql = statementHandler.getBoundSql();

            if(configuration ==null){
                final DefaultParameterHandler parameterHandler = (DefaultParameterHandler) statementHandler.getParameterHandler();
                Field configurationField = ReflectionUtils.findField(parameterHandler.getClass(), "configuration");
                ReflectionUtils.makeAccessible(configurationField);
                this.configuration =  (Configuration) configurationField.get(parameterHandler);
            }

            // 格式化Sql语句，去除换行符，替换参数
            String sql = formatSQL(boundSql, configuration);

            if (timeCount > 1000) {
                log.error("慢SQL\n执行 SQL：[ {} ]\n执行耗时: {} ms", sql, timeCount);
            } else {
                log.info("SQL执行监听\n执行 SQL：[ {} ]\n执行耗时: {} ms", sql, timeCount);
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 格式化/美化 SQL语句
     * @return 格式化之后的SQL
     */
    private String formatSQL(BoundSql boundSql, Configuration configuration) {
        String sql = boundSql.getSql();
        // 输入sql字符串空判断
        if (StringUtils.isEmpty(sql)) {
            return "";
        }
        if (StringUtils.isNull(configuration)) {
            return "";
        }
        // 获取传入对象
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        // 美化sql
        sql = beautifySql(sql);
        // 获取参数组装sql
        if (StringUtils.isNotNull(parameterObject) && StringUtils.isNotEmpty(parameterMappings)) {
            for (ParameterMapping parameterMapping : parameterMappings) {
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else {
                        MetaObject metaObject = configuration.newMetaObject(parameterObject);
                        value = metaObject.getValue(propertyName);
                    }
                    String paramValueStr = "";
                    if(value instanceof String){
                        paramValueStr = "'" + value + "'";
                    }else if (value instanceof Date) {
                        paramValueStr = "'" + DATE_FORMAT_THREAD_LOCAL.get().format(value) + "'";
                    } else {
                        paramValueStr =  value + "";
                    }
                    // mybatis generator 中的参数不打印出来
//                    if(!propertyName.contains("frch_criterion")){
//                        paramValueStr = "/*" + propertyName + "*/" + paramValueStr;
//                    }
                    sql = sql.replaceFirst("\\?", paramValueStr);
                }
            }
        }
        return sql;
    }

    /**
     * 美化sql
     *
     * @param sql sql语句
     */
    private String beautifySql(String sql) {
        sql = sql.replaceAll("[\\s\n ]+", "  ");
        return sql;
    }


}
